<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>登录 - IM聊天室</title>
    <link rel="icon" href="img/chat.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="css/font-awesome.css"/>
    <link rel="stylesheet" href="css/login.css" type="text/css" media="all"/>

    <!-- 内联按钮样式，确保渲染成功 -->
    <style>
        #loginBtn {
            width: 100%;
            background: linear-gradient(to right, #4facfe, #00f2fe);
            border: none;
            color: white;
            padding: 12px;
            font-size: 16px;
            border-radius: 30px;
            cursor: pointer;
            transition: background 0.3s, transform 0.2s;
            margin-top: 20px;
            position: relative;
        }

        #loginBtn:hover {
            background: linear-gradient(to right, #43e97b, #38f9d7);
            transform: scale(1.05);
        }

        .loading-spinner {
            width: 16px;
            height: 16px;
            border: 2px solid #fff;
            border-top: 2px solid transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-left: 8px;
            vertical-align: middle;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .error-message {
            color: red;
            margin-top: 10px;
        }
    </style>
</head>

<body class="background">
<div class="header-w3l">
    <h1>IM聊天室</h1>
</div>

<div class="main-content-agile">
    <div class="sub-main-w3">
        <h2>用户登录</h2>
        <form id="loginForm">
            <div class="input-group">
                <div class="icon1">
                    <input placeholder="用户名" id="username" type="text" required autocomplete="username"/>
                </div>
                <div class="icon2">
                    <input placeholder="密码" id="password" type="password" required autocomplete="current-password"/>
                </div>
            </div>

            <div class="form-footer">
                <button type="submit" id="loginBtn" class="btn-login">
                    <span class="btn-text">登 录</span>
                    <span class="loading-spinner" hidden></span>
                </button>
                <div class="links">
                    <a href="register.html">没有账号？立即注册</a>
                </div>
                <div id="errorMsg" class="error-message"></div>
            </div>
        </form>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const loginForm = document.getElementById("loginForm");
        const usernameInput = document.getElementById("username");
        const passwordInput = document.getElementById("password");
        const errorMsg = document.getElementById("errorMsg");
        const loginBtn = document.getElementById("loginBtn");
        const loadingSpinner = loginBtn.querySelector('.loading-spinner');

        loginForm.addEventListener("submit", async (e) => {
            e.preventDefault();
            errorMsg.textContent = '';
            loginBtn.disabled = true;
            loadingSpinner.hidden = false;
            loginBtn.querySelector('.btn-text').textContent = '登录中...';

            try {
                const username = usernameInput.value.trim();
                const password = passwordInput.value.trim();

                if (!username || !password) {
                    throw new Error('用户名和密码不能为空');
                }

                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时

                const response = await fetch('/user/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password }),
                    signal: controller.signal
                }).catch(err => {
                    throw new Error('请求发送失败或超时：' + err.message);
                });
                clearTimeout(timeoutId);

                console.log("响应状态码:", response.status);

                const result = await response.json().catch(() => {
                    throw new Error('无法解析 JSON 响应');
                });

                console.log("响应数据:", result);

                if (!response.ok || result.code !== 200) {
                    throw new Error(result.message || '登录失败');
                }

                sessionStorage.setItem('authToken', result.data?.token || '');
                sessionStorage.setItem('username', username);
                window.location.href = '/index.html';

            } catch (error) {
                console.error('登录错误:', error);
                errorMsg.textContent = error.message || '登录请求失败';
            } finally {
                loginBtn.disabled = false;
                loadingSpinner.hidden = true;
                loginBtn.querySelector('.btn-text').textContent = '登 录';
            }

        });

        [usernameInput, passwordInput].forEach(input => {
            input.addEventListener('input', () => {
                if (input.value.trim()) {
                    input.classList.remove('invalid');
                }
            });
        });
    });
</script>
</body>
</html>
